package com.charmzenus.it.order.controller;


import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;


@RestController
@RequestMapping("/hystrix")
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {

    private Logger logger = LoggerFactory.getLogger(HystrixController.class);

//    @HystrixCommand(fallbackMethod = "fallBack")

    // 超时配置
//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
//    })

    // 熔断
//    @HystrixCommand(commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),                  // 设置熔断
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),     // 断路器最小请求数
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),  // 休眠时间窗，
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),   // 滚动时间窗口中， 60%异常的时候，就会打开断路器
//    })
    @HystrixCommand(commandKey = "Demo")
    @GetMapping("/getList")
    public String getList() {

        try {
            Thread.sleep(2000);
            // 很多业务逻辑

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("hello11111");
        }
//
//
//        // 这里如果请求的服务发生了异常（就是说请求的服务宕机了，返回500）， 或者抛出异常了，都会进行服务降级，调用fallBack方法
//        RestTemplate restTemplate = new RestTemplate();
//
//        String url = "http://127.0.0.1:8081/member/getList";
//        String result = restTemplate.postForObject(url, Arrays.asList("123465"), String.class);
//
//        logger.info("getList   success");
//
//        System.out.println(result);



        return "hello";

//        throw new RuntimeException("error");


    }



    /**
     * 出故障了
     *
     * @return
     */
    private String fallBack() {
        return "服务器繁忙，请稍后再试";
    }


    private String defaultFallback() {
        return "默认: 服务器繁忙，请稍后再试";
    }
}
